package com.newasia.server.serviceImpl;

import com.newasia.server.common.exception.ExceptionUtil;
import com.newasia.server.common.interceptor.page.PageConfig;
import com.newasia.server.common.interceptor.page.PageMess;
import com.newasia.server.common.proxy.DataConversionProxy;
import com.newasia.server.common.result.ResponseData;
import com.newasia.server.common.template.ConfigReader;
import com.newasia.server.common.template.ModuleAnalysisTemplate;
import com.newasia.server.common.template.dataItem.basics.CurrentStatus;
import com.newasia.server.dal.entitys.*;
import com.newasia.server.dal.entitys.returnValue.MonitorState;
import com.newasia.server.dal.persistence.*;
import com.newasia.server.service.*;
import com.newasia.server.serviceImpl.manage.MonitorDetailManage;
import com.newasia.server.serviceImpl.manage.MonitorStateListManage;
import com.newasia.server.serviceImpl.manage.MonitorStateManage;
import com.newasia.server.serviceImpl.manage.SubmitMachine;
import com.newasia.server.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.newasia.server.common.tool.CheckObjectIsNullUtils.checkObjIsNull;

/**
 * @author LiChong
 * @description 监控点数据获取服务
 * @date 2020/4/10
 */
@Slf4j
@Service
public class MonitorServiceImpl implements IMonitorService {

    IMonitorDetailService monitorDetailService = (IMonitorDetailService)new DataConversionProxy().getInstance(MonitorDetailServiceImpl.class);
    IMonitorDetailBakService MonitorDetailBakService = (IMonitorDetailBakService)new DataConversionProxy().getInstance(MonitorDetailBakServiceImpl.class);
    IHistoryService historyService = (IHistoryService)new DataConversionProxy().getInstance(HistoryServiceImpl.class);

    @Autowired(required = false)
    MonitorMapper monitorMapper;
    @Autowired(required = false)
    ModuleNameMapper moduleNameMapper;
    @Autowired(required = false)
    MonitorSubMapper monitorSubMapper;
    @Autowired(required = false)
    SidMonitorModeMapper sidMonitorModeMapper;
    @Autowired(required = false)
    IHisAlertService hisAlertService;
    @Autowired(required = false)
    ActiveMapper activeMapper;

    /**
     *获取账户的全部监控点
     * @author LiChong
     * @date 2020/5/6
     * @param  * @param userId
     * @return com.newasia.server.common.result.ResponseData
     */
    @Override
    public ResponseData getMonitorStatusList() {
        ResponseData responseData = new ResponseData();
        Long userId = ShiroUtils.getUserInfo().getUserId();
        try{
            MonitorStateListManage monitorStateListManage = new MonitorStateListManage();
            List<MonitorState> monitorStates = MonitorDetailBakService.getMonitorsStatusByUserId(userId);
            //放置长度
            monitorStateListManage.setQuantity(monitorStates.size());
            for (MonitorState monitorState:monitorStates) {
                MonitorStateManage manage = new MonitorStateManage(monitorState);
                //添加至对应的排序分组列表中
                monitorStateListManage.addMonitorStateManage(manage);
            }
            responseData.setResult(monitorStateListManage);
        }catch (Exception e){
            log.error("MonitorServiceImpl.getMonitorsStatusByUserId Exception"+e);
            e.printStackTrace();
            return ExceptionUtil.handlerException4biz(responseData,e);
        }
        return responseData;
    }

    @Override
    public ResponseData getModule(Long moduleId) {
        ResponseData responseData = new ResponseData();
        try{
            //MonitorDetail monitorDetail = monitorDetailService.getMonitorDetail(sid);
            //monitorDetail.getTemplate();
            responseData.setResult(ConfigReader.doLoadConfig(moduleId));
        }catch (Exception e){
            e.printStackTrace();
        }
        return responseData;
    }

    @Override
    public ResponseData getMonitorDetail(String sid) {
        ResponseData responseData = new ResponseData();
        Long userId = ShiroUtils.getUserInfo().getUserId();
        String userName = ShiroUtils.getUserInfo().getUserName();
        MonitorDetailManage monitorDetailManage = new MonitorDetailManage();
        try{
            //监控点即时信息
            MonitorDetail detail = monitorDetailService.getMonitorDetail(sid);
            if(checkObjIsNull(detail)){
                return responseData;
            }
            //更新时间
            monitorDetailManage.setUploadTime(detail.getUploadTime());

            //获取数据解析器
            ModuleAnalysisTemplate template = detail.getTemplate();

            //个性化监控点信息
            SidMonitorMode sidMonitorMode = sidMonitorModeMapper.selectBySidAndUserId(sid,userId);
            long monitorId = sidMonitorMode.getMonitorId();
            //监控点主信息
            Monitor monitor = monitorMapper.selectByPrimaryKey(monitorId);
            //判断是否是主账号
            if(Long.compare(monitor.getUserId(),userId)==0){
                monitorDetailManage.setPermission(4);
            }else{
                monitorDetailManage.setPermission(sidMonitorMode.getControlLevel());
            }
            //判断是否置顶
            monitorDetailManage.setIsTop(sidMonitorMode.getIsTop());
            //放入型号
            Long moduleId = detail.getModuleId();
            monitorDetailManage.setModuleId(moduleId);
            monitorDetailManage.setModuleName(detail.getModuleName());
            //查找是否为主从机
            ModuleName moduleName = moduleNameMapper.selectByPrimaryKey(detail.getModuleId());
            Long isSub = moduleName.getIsSub();
            monitorDetailManage.setIsSub(isSub);
            //可变更的从机数量
            Integer subSize = 0;
            //是否可设置从机数目
            boolean subChange = false;
            //从机列表
            List<SubmitMachine> submitMachines = new ArrayList<SubmitMachine>();
            //假如为主机的话
            if(Long.compare(isSub,2)==0){
                //根据主从机表的记录进行筛选
                List<String> sids = monitorSubMapper.selectSidsByMainSid(sid);

                if(sids.size()==0){
                    //若从机数量为0，则未设置从机数量，查询最大可设置值
                    subSize = monitorSubMapper.countByMainSid(sid);
                    subChange = true;
                }else {
                    //若从机数量不为0，则遍历从机信息
                    List<SidMonitorMode> subs = sidMonitorModeMapper.selectBySidsAndUserId(sids,userId);
                    for (SidMonitorMode sub:subs) {
                        SubmitMachine submitMachine = new SubmitMachine();
                        submitMachine.setMonitorId(sub.getMonitorId());
                        submitMachine.setMonitorName(sub.getMonitorName());
                        submitMachine.setSid(sub.getSid());
                        submitMachines.add(submitMachine);
                    }
                }
            }
            monitorDetailManage.setIsChangeSub(subChange);
            monitorDetailManage.setSubSize(subSize);
            monitorDetailManage.setSubmitMachines(submitMachines);

            ///获取显示项
            monitorDetailManage.setShowData(template.getShowData());
            //检测是否离线
            CurrentStatus currentStatus = new CurrentStatus();
            boolean flagOffline = true;
            try {
                Date upload_time = detail.getUploadTime();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(upload_time);
                calendar.set(Calendar.MINUTE,
                        calendar.get(Calendar.MINUTE) + 20);
                upload_time = calendar.getTime();
                Date date = new Date();
                if (upload_time.getTime() > date.getTime()) {
                    flagOffline = false;
                }
            }catch(Exception e1){
                e1.printStackTrace();
            }
            if (!flagOffline) {
                if (detail.getFlagAlert()) {
                    currentStatus.setStateFlag(1);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("key", 1);
                    map.put("value", "告警中");
                    currentStatus.setState(map);

                    //获取监控点告警信息
                    HisAlert alert = hisAlertService.selectHisAlertSequence(sid);
                    if(alert!=null) {
                        monitorDetailManage.setAlert(alert);
                    }
                }else
                    currentStatus = template.getCurrentStatus();
            }else {
                currentStatus.setStateFlag(-1);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("key",-1);
                map.put("value","离线中");
                currentStatus.setState(map);
            }
            monitorDetailManage.setStatus(currentStatus);
            monitorDetailManage.setWiFi(template.isWiFi());
            monitorDetailManage.setBootOptions(template.getBootOptions());
            monitorDetailManage.setMaintain(template.isMaintain());
            monitorDetailManage.setPwPass(detail.getPwPass());
            monitorDetailManage.setActivation(template.isActivation());
            monitorDetailManage.setDoorOpenMonthTime(template.countDoorOpenMonthTime());
            monitorDetailManage.setDoorOpenTotalTime(template.countDoorOpenTotalTime());

            //PageHelper.startPage(1,10);//这行是重点，表示从pageNum页开始，每页pageSize条数据
            PageConfig.startPage(1,5,"timer8");
            List<History> histories = historyService.count(sid,moduleId);
            //List<MonitorState> monitorStates = MonitorDetailBakService.getMonitorsStatusByUserId(userId);
            //PageInfo<MonitorState> pageInfo = new PageInfo<MonitorState>(monitorStates);
            PageMess<History> pageMess = new PageMess<>(histories);
            //System.out.println(pageMess);
            //System.out.println(pageInfo);
            Active active = activeMapper.selectByPrimaryKey(sid);
            if(!checkObjIsNull(active)){
                Date time = active.getTime();
                System.out.println(template.getDefrosterElectricity());
                System.out.println(template.getRefrigerationElectricity());
            }
            responseData.setResult(pageMess);
            //responseData.setResult(monitorDetailManage);
            /*String use_name = request.getParameter("userName");
            String monitor_id = request.getParameter("monitor_id");
            //获取监控点基本信息
            HashMap<String,Object> monitor = new HashMap<String,Object>();
            monitor = monitorService.getNewMonitorDetail(monitor_id,use_name);
            -------------------------------------------------------------------------------

            for(int i=1;i<size;i++) {

                String name = configs.get("data"+i).get("name");
                if(name == "制冷总电量"||name.equals("制冷总电量")) {
                    String val = "";
                    String cal = "--";
                    if(monitor.get("db"+i)!=null){
                        val = String.valueOf(monitor.get("db"+i));
                        //得到转换的数据
                        cal = ValuetextUtil.getDataByValuetext(val,configs.get("data"+i).get("valuetext"));
                    }
                    if(val==null||val.equals("")) {
                        info.put("electricity",0);
                        break;
                    }
                    //本月用电量计算
                    String num = historyService.getDataBySid(sid);
                    DateFormat ydf = new SimpleDateFormat("yyyy");
                    DateFormat mdf = new SimpleDateFormat("MM");
                    DateFormat ymdf = new SimpleDateFormat("yyyy-MM");

                    HashMap<String,Object> active = new HashMap<String,Object>();
                    String yyyyMM = null;
                    try {
                        active = walletService.getActiveSid(sid);
                        yyyyMM = ymdf.format(active.get("time"));
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                    Date time = new Date();
                    String year = ydf.format(time);
                    String mon = mdf.format(time);
                    Integer electricity = 0;
                    if(yyyyMM != (year+"-"+mon)&&!(year+"-"+mon).equals(yyyyMM)) {
                        electricity = historyService.getElectricityHisDataBySid(sid, num, "db"+i,year,mon);
                    }
                    if(electricity==null||electricity.equals("")) {
                        electricity = 0;
                    }
                    Double elect = Double.valueOf(ValuetextUtil.getDataByValuetext(electricity.toString(),configs.get("data"+i).get("valuetext")));
                    elect = Double.valueOf(cal)-elect;
                    info.put("ref_elect",elect);
                    info.put("ref_elect_id",i);
                    break;
                }
            }
            if(sid=="808051101016"||sid.equals("808051101016")||
                    sid=="808051101740"||sid.equals("808051101740")) {
                info.put("ref_elect",0);
                info.put("ref_elect_id",100);
                info.put("def_elect",0);
                info.put("def_elect_id",101);
            }
            info.put("request_status", "true");
            return info;*/
        }catch (Exception e){
            log.error("MonitorServiceImpl.getMonitorDetail Exception"+e);
            e.printStackTrace();
            return ExceptionUtil.handlerException4biz(responseData,e);
        }
        return responseData;
    }
}
